<template>
  <el-select
    v-model="selectValue"
    placeholder=""
    :style="stylesConfig"
    @change="handleSelectChange"
    class="compo-public-style"
    v-if="preview"
  >
    <el-option
      v-for="item in dynamicData || mockData"
      :key="item.label"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
  <el-input
    :style="stylesConfig"
    placeholder="select"
    :disabled="true"
    v-else
  ></el-input>
</template>

<script setup>
import { ref, computed, onBeforeUnmount, onMounted, toRef, toRefs } from 'vue';
import emitter from '@/utils/bus.js';

let timer = null;

const mockData = [
  {
    label: '2022年',
    value: '2022'
  },
  {
    label: '2021年',
    value: '2021'
  }
];

const props = defineProps({
  value: {
    type: Object,
    default: () => {}
  },
  preview: {
    type: Boolean,
    default: () => false
  }
});
const { setups, styles, data } = toRefs(props.value);

const preview = toRef(props, 'preview');

const selectValue = ref('');

const dynamicData = ref(null); //动态数据初始值

/**
 * @description:样式配置
 * @param {*} computed
 * @return {*}
 */
const stylesConfig = computed(() => {
  return {
    width: `${styles.value?.w / 100}rem`,
    height: `${styles.value?.h / 100}rem`,
    position: preview.value ? 'absolute' : 'static',
    left: `${styles.value?.x}px`,
    top: `${styles.value?.y}px`
  };
});

// /**
//  * @description:初始数据
//  * @param {*} computed
//  * @return {*}
//  */
// const initData = computed(() => {
//     return data.value;
// });

/**
 * @description:获取动态数据
 * @param {对象} value查询参数
 * @return {*}
 */
const getDynamicData = async (value) => {
  let res = await Promise.resolve([
    {
      label: '2023年',
      value: '2023'
    },
    {
      label: '2022年',
      value: '2022'
    },
    {
      label: '2021年',
      value: '2021'
    }
  ]);

  dynamicData.value = res;
};

preview.value && getDynamicData();

/**
 * @description:定时刷新数据
 * @return {*}
 */
const refreshData = () => {
  if (preview.value) {
    timer = setInterval(() => {
      // console.log('widget-select-定时请求来了');
      getDynamicData();
    }, 50000);
  }
};
onBeforeUnmount(() => {
  clearInterval(timer);
  timer = null;
});

onMounted(() => {
  refreshData();
});

/**
 * @description:值改变触发其它组件的联动,传值
 * @param {*} value
 * @return {*}
 */
const handleSelectChange = (value) => {
  console.log('select-component', setups.value, value);
  if (setups.value.linkageSetting.action === 'valueChange') {
    setups.value.linkageSetting?.events.forEach((element) => {
      console.log('************', element.linkageStatus, element.id);
      element.linkageStatus &&
        emitter.emit(element.id, { name: 'select变化传过来的值', age: 20 });
    });
  }
};
</script>
<style scoped lang="scss"></style>
